package com.zyy.seckill.vo;

import com.zyy.seckill.utils.ValidatorUtil;
import com.zyy.seckill.validator.IsMobile;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 手机号验证规则校验
 *
 * @Author: zyy
 * @DateTime: 2021/10/3 19:56
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    /**
     * 初始化操作
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required) {
            return ValidatorUtil.isMobile(value);
        }

        if (!StringUtils.hasLength(value)) {
            return true;
        } else {
            return ValidatorUtil.isMobile(value);
        }

    }
}
